package com.example.rouroudate.ui.widget

import android.util.Log
import android.widget.AbsListView
import android.widget.LinearLayout
import android.widget.TextView
import kotlin.math.abs

class DateScrollListener(private val scrollCallback: DateScrollCallback, private val type: Int): AbsListView.OnScrollListener {
    companion object {
        const val TAG = "DateScrollListener"
    }
    override fun onScrollStateChanged(p0: AbsListView?, p1: Int) {
        when(p1) {
            AbsListView.OnScrollListener.SCROLL_STATE_IDLE -> {
                Log.d(TAG, "SCROLL_STATE_IDLE")

                p0?.let {
                    val view = p0.getChildAt(0)
                    val position = p0.firstVisiblePosition + p0.childCount / 2
                    val top = view.top
                    val height = view.measuredHeight
                    val offset = ((p0.measuredHeight - height) / 2) % height - height
                    Log.d(TAG, "text = ${((view as LinearLayout).getChildAt(0) as TextView).text}")
                    if (top == offset) {
                        scrollCallback.onScrollEnd(position, type)
                    } else if (abs(top) * 2 > height) {
                        p0.smoothScrollBy( top + height - offset, 300)
                    } else {
                        if (abs(offset) > height / 2) {
                            p0.smoothScrollBy(offset - top, 300)
                        } else {
                            p0.smoothScrollBy(top - offset, 300)
                        }
                    }
                }
            }
            AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL -> {
                Log.d(TAG, "SCROLL_STATE_TOUCH_SCROLL")
            }
            else -> {
                Log.d(TAG, "else")
            }
        }
    }

    override fun onScroll(p0: AbsListView?, p1: Int, p2: Int, p3: Int) {

    }
}